#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SMIS配料岛库存数据处理脚本
用于读取SMIS配料岛库存数据并转换为标准格式
"""

import json
import os
from datetime import datetime
from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.parse
import threading

# 配置
DATA_FILE_PATH = r"c:\Users\renshuai\Desktop\SMIS配料岛库存数据.txt"
ORGANIZATION_NAME = "银河航天科技（南通）有限公司"

def load_smis_data():
    """
    加载SMIS配料岛库存数据 - 直接读取txt文件内容（无缓存）
    """
    print(f"[读取文件] {DATA_FILE_PATH}")
    
    try:
        if not os.path.exists(DATA_FILE_PATH):
            return {"success": False, "error": f"数据文件不存在: {DATA_FILE_PATH}"}
        
        file_start_time = datetime.now().timestamp()
        with open(DATA_FILE_PATH, 'r', encoding='utf-8') as file:
            # 直接读取文件内容
            file_content = file.read().strip()
            
            # 尝试解析为JSON
            try:
                data = json.loads(file_content)
                result = {"success": True, "data": data, "raw_content": file_content}
            except json.JSONDecodeError:
                # 如果不是JSON格式，直接返回原始内容
                result = {"success": True, "data": file_content, "raw_content": file_content}
        
        file_read_time = datetime.now().timestamp() - file_start_time
        print(f"[文件读取] 耗时: {file_read_time:.3f}秒, 文件大小: {len(file_content)} 字符")
        
        return result
    
    except Exception as e:
        print(f"[文件读取错误] {str(e)}")
        return {"success": False, "error": f"读取文件失败: {str(e)}"}

def convert_smis_to_u9_format(smis_data):
    """
    直接返回原始数据，不做任何转换
    """
    return smis_data

class SMISRequestHandler(BaseHTTPRequestHandler):
    """
    SMIS配料岛库存数据HTTP请求处理器
    """
    
    def _set_cors_headers(self):
        """设置CORS头"""
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
    
    def _send_json_response(self, data, status_code=200):
        """发送JSON响应"""
        json_data = json.dumps(data, ensure_ascii=False, indent=2)
        self.send_response(status_code)
        self.send_header('Content-Type', 'application/json; charset=utf-8')
        self._set_cors_headers()
        self.end_headers()
        self.wfile.write(json_data.encode('utf-8'))
    
    def do_OPTIONS(self):
        """处理OPTIONS请求（CORS预检）"""
        self.send_response(200)
        self._set_cors_headers()
        self.end_headers()
    
    def do_POST(self):
        """处理POST请求"""
        self._send_json_response({
            "success": False,
            "error": "POST请求不支持，请使用GET /api/smis/raw获取原始数据"
        }, 405)
    
    def do_GET(self):
        """处理GET请求"""
        if self.path == '/':
            self.handle_api_docs()
        elif self.path == '/api/smis/raw':
            self.handle_raw_data()
        elif self.path == '/health':
            self.handle_health_check()
        else:
            self._send_json_response({
                "success": False,
                "error": f"未找到路径: {self.path}"
            }, 404)
    
    def handle_health_check(self):
        """处理健康检查请求"""
        self._send_json_response({
            "status": "healthy",
            "service": "SMIS配料岛库存数据服务",
            "timestamp": datetime.now().isoformat()
        })
    
    def log_message(self, format, *args):
        """自定义日志格式"""
        print(f"[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] {format % args}")

    def handle_api_docs(self):
        """处理API文档请求"""
        html_content = """
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>SMIS配料岛库存数据服务</title>
            <style>
                body { 
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; 
                    max-width: 800px; 
                    margin: 50px auto; 
                    padding: 20px; 
                    line-height: 1.6; 
                }
                .header { 
                    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); 
                    color: white; 
                    padding: 20px; 
                    border-radius: 10px; 
                    margin-bottom: 30px; 
                }
                .endpoint { 
                    background: #f8f9fa; 
                    border-left: 4px solid #007bff; 
                    padding: 15px; 
                    margin: 15px 0; 
                    border-radius: 5px; 
                }
                .method { 
                    display: inline-block; 
                    padding: 4px 8px; 
                    border-radius: 4px; 
                    font-weight: bold; 
                    font-size: 12px; 
                }
                .get { background: #28a745; color: white; }
                .post { background: #007bff; color: white; }
                code { 
                    background: #f1f3f4; 
                    padding: 2px 6px; 
                    border-radius: 3px; 
                    font-family: 'Courier New', monospace; 
                }
                .status { 
                    color: #28a745; 
                    font-weight: bold; 
                }
            </style>
        </head>
        <body>
            <div class="header">
                <h1>🏭 SMIS配料岛库存数据服务</h1>
                <p>银河航天科技（南通）有限公司 - 配料岛库存管理系统后端服务</p>
            </div>
            
            <div class="status">✅ 服务状态：正常运行</div>
            <p><strong>服务地址：</strong> http://localhost:5002</p>
            <p><strong>组织名称：</strong> 银河航天科技（南通）有限公司</p>
            
            <h2>📋 API接口列表</h2>
            
            <div class="endpoint">
                <div><span class="method get">GET</span> <code>/health</code></div>
                <p><strong>功能：</strong>健康检查</p>
                <p><strong>示例：</strong><a href="/health" target="_blank">点击测试</a></p>
            </div>
            
            <div class="endpoint">
                <div><span class="method get">GET</span> <code>/api/smis/raw</code></div>
                <p><strong>功能：</strong>获取SMIS配料岛原始数据（JSON格式）</p>
                <p><strong>示例：</strong><a href="/api/smis/raw" target="_blank">点击测试</a></p>
                <p><strong>说明：</strong>直接返回txt文件的原始内容，数据过滤和处理由前端完成</p>
            </div>
            
            <h2>🔧 使用说明</h2>
            <ul>
                <li>本服务只提供SMIS配料岛原始数据接口</li>
                <li>数据过滤、查询和处理由前端JavaScript完成</li>
                <li>服务器只负责读取本地txt文件并返回原始数据</li>
                <li>前端应用地址：<a href="http://localhost:5173" target="_blank">http://localhost:5173</a></li>
            </ul>
            
            <h2>📊 数据字段映射</h2>
            <table border="1" style="border-collapse: collapse; width: 100%;">
                <tr style="background: #f8f9fa;">
                    <th style="padding: 8px;">SMIS字段</th>
                    <th style="padding: 8px;">U9字段</th>
                    <th style="padding: 8px;">说明</th>
                </tr>
                <tr>
                    <td style="padding: 8px;">materialcode</td>
                    <td style="padding: 8px;">ItemCode</td>
                    <td style="padding: 8px;">物料编码</td>
                </tr>
                <tr>
                    <td style="padding: 8px;">materialname</td>
                    <td style="padding: 8px;">ItemName</td>
                    <td style="padding: 8px;">物料名称</td>
                </tr>
                <tr>
                    <td style="padding: 8px;">materialgg</td>
                    <td style="padding: 8px;">ItemSpec</td>
                    <td style="padding: 8px;">型号规格</td>
                </tr>
                <tr>
                    <td style="padding: 8px;">venderlot</td>
                    <td style="padding: 8px;">LotCode</td>
                    <td style="padding: 8px;">批次号</td>
                </tr>
                <tr>
                    <td style="padding: 8px;">warehousename</td>
                    <td style="padding: 8px;">WhName</td>
                    <td style="padding: 8px;">仓库名称</td>
                </tr>
                <tr>
                    <td style="padding: 8px;">total</td>
                    <td style="padding: 8px;">StoreQty</td>
                    <td style="padding: 8px;">库存数量</td>
                </tr>
            </table>
            
            <div style="margin-top: 30px; text-align: center; color: #666;">
                <p>SMIS配料岛库存数据服务 - 版本 1.0</p>
                <p>© 银河航天科技（南通）有限公司</p>
            </div>
        </body>
        </html>
        """
        
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=utf-8')
        self._set_cors_headers()
        self.end_headers()
        self.wfile.write(html_content.encode('utf-8'))

    def handle_raw_data(self):
        """处理原始数据请求 - 直接返回文件内容"""
        try:
            load_result = load_smis_data()
            if not load_result['success']:
                self._send_json_response({
                    "success": False,
                    "error": load_result['error']
                }, 500)
                return
            
            # 直接返回原始数据，不做任何处理
            raw_data = load_result['data']
            
            # 如果是JSON格式，直接返回解析后的数据
            if isinstance(raw_data, dict) or isinstance(raw_data, list):
                self._send_json_response(raw_data)
            else:
                # 如果是字符串，尝试解析为JSON后返回
                try:
                    parsed_data = json.loads(raw_data)
                    self._send_json_response(parsed_data)
                except json.JSONDecodeError:
                    # 如果不是JSON格式，返回纯文本
                    self.send_response(200)
                    self.send_header('Content-Type', 'text/plain; charset=utf-8')
                    self._set_cors_headers()
                    self.end_headers()
                    self.wfile.write(raw_data.encode('utf-8'))
            
        except Exception as e:
            self._send_json_response({
                "success": False,
                "error": f"获取原始数据失败: {str(e)}"
            }, 500)

def start_server():
    """启动HTTP服务器"""
    server_address = ('', 5002)
    httpd = HTTPServer(server_address, SMISRequestHandler)
    
    print(f"正在启动SMIS配料岛库存数据服务...")
    print(f"数据文件路径: {DATA_FILE_PATH}")
    print(f"组织名称: {ORGANIZATION_NAME}")
    
    # 预检查数据文件
    print("正在检查数据文件...")
    preload_result = load_smis_data()
    if preload_result['success']:
        print("✅ 数据文件检查成功")
    else:
        print(f"⚠️ 数据文件检查失败: {preload_result['error']}")
    
    print(f"服务地址: http://localhost:5002")
    print(f"原始数据接口: GET /api/smis/raw")
    print(f"健康检查接口: GET /health")
    print(f"服务器启动成功，按Ctrl+C停止服务")
    
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n正在停止服务器...")
        httpd.server_close()
        print("服务器已停止")

if __name__ == '__main__':
    start_server()
